<template>
  <div class="production-plan">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>
            <el-icon><Calendar /></el-icon>
            生产计划管理
          </h2>
          <p>制定和管理生产计划，合理安排生产任务</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新建生产计划
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="计划编号">
          <el-input v-model="searchForm.planNo" placeholder="请输入计划编号" clearable />
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total }}</div>
                <div class="stat-label">总计划数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.executing }}</div>
                <div class="stat-label">执行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.delayed }}%</div>
                <div class="stat-label">计划完成率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" stripe border v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planNo" label="计划编号" width="180" fixed />
        <el-table-column prop="planName" label="计划名称" min-width="200" />
        <el-table-column prop="product" label="产品名称" width="180" />
        <el-table-column prop="quantity" label="计划数量" width="120" align="right">
          <template #default="{ row }">
            <el-tag>{{ row.quantity }} {{ row.unit }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="计划开始" width="120" />
        <el-table-column prop="endDate" label="计划完成" width="120" />
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :color="getProgressColor(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon> 查看
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)" v-if="row.status === 'draft'">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button link type="success" size="small" @click="handleApprove(row)" v-if="row.status === 'pending'">
              <el-icon><CircleCheck /></el-icon> 审核
            </el-button>
            <el-button link type="warning" size="small" @click="handleExecute(row)" v-if="row.status === 'approved'">
              <el-icon><VideoPlay /></el-icon> 执行
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)" v-if="row.status === 'draft'">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划编号" prop="planNo">
              <el-input v-model="formData.planNo" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productId">
              <el-select v-model="formData.productId" placeholder="请选择产品" filterable>
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划数量" prop="quantity">
              <el-input-number v-model="formData.quantity" :min="1" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="formData.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成日期" prop="endDate">
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="选择完成日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产车间" prop="workshopId">
              <el-select v-model="formData.workshopId" placeholder="请选择车间">
                <el-option label="第一车间" value="1" />
                <el-option label="第二车间" value="2" />
                <el-option label="第三车间" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择优先级">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar, Plus, Search, RefreshLeft, Document, Loading,
  CircleCheck, Clock, View, Edit, Delete, VideoPlay
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  planNo: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  total: 156,
  executing: 23,
  completed: 118,
  delayed: 85.6
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新建生产计划')
const formRef = ref(null)

// 产品选项
const productOptions = ref([
  { id: '1', name: '产品A' },
  { id: '2', name: '产品B' },
  { id: '3', name: '产品C' }
])

// 表单数据
const formData = reactive({
  planNo: '',
  planName: '',
  productId: '',
  quantity: 1,
  startDate: '',
  endDate: '',
  workshopId: '',
  priority: 'medium',
  remark: ''
})

// 表单验证规则
const formRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择完成日期', trigger: 'change' }],
  workshopId: [{ required: true, message: '请选择生产车间', trigger: 'change' }]
}

// 获取表格数据
const fetchData = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        planNo: 'PLAN202501001',
        planName: '2025年1月份A产品生产计划',
        product: '产品A',
        quantity: 1000,
        unit: '件',
        startDate: '2025-01-01',
        endDate: '2025-01-31',
        progress: 65,
        status: 'executing',
        creator: '张三'
      },
      {
        id: '2',
        planNo: 'PLAN202501002',
        planName: '2025年1月份B产品生产计划',
        product: '产品B',
        quantity: 500,
        unit: '件',
        startDate: '2025-01-05',
        endDate: '2025-01-25',
        progress: 100,
        status: 'completed',
        creator: '李四'
      },
      {
        id: '3',
        planNo: 'PLAN202501003',
        planName: '2025年1月份C产品生产计划',
        product: '产品C',
        quantity: 800,
        unit: '件',
        startDate: '2025-01-10',
        endDate: '2025-02-10',
        progress: 35,
        status: 'executing',
        creator: '王五'
      }
    ]
    pagination.total = 3
    loading.value = false
  }, 500)
}

// 进度颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    executing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    pending: '待审核',
    approved: '已审核',
    executing: '执行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    planNo: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

// 显示新建对话框
const showAddDialog = () => {
  dialogTitle.value = '新建生产计划'
  Object.assign(formData, {
    planNo: 'PLAN' + Date.now(),
    planName: '',
    productId: '',
    quantity: 1,
    startDate: '',
    endDate: '',
    workshopId: '',
    priority: 'medium',
    remark: ''
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看计划详情：' + row.planNo)
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑生产计划'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 审核
const handleApprove = (row) => {
  ElMessageBox.confirm('确定审核通过该生产计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('审核成功')
    fetchData()
  })
}

// 执行
const handleExecute = (row) => {
  ElMessageBox.confirm('确定开始执行该生产计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('已开始执行')
    fetchData()
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该生产计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.production-plan {
  padding: 20px;

  .header-card {
    margin-bottom: 20px;
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        h2 {
          display: flex;
          align-items: center;
          gap: 10px;
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #303133;
        }

        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 20px;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 20px;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 28px;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
}
</style>

